package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerRelationDepPerson.DepartmentPerson;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 部门人员详情
 *
 * @author wu
 */
public class CustomerRelationStaffDetailFragment extends BaseFragment {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  protected static final String TAG = CustomerRelationStaffDetailFragment.class.getName();
  private static final int REQUEST_ALTER = 0;
  private static final int REQUEST_DELETE = 2;
  private static final int REQUESUT_SUBMIT = 1;
  HashMap<String, String> mDepartmentDetail;
  private BaseVolleyActivity mActivity;
  private TextView tvDirectorNumberDetail;// 编号
  private TextView tvDepartmentpersonDetail;// 姓名
  private TextView tv_personGender_detail;// 性别
  private TextView tvDirectordialDetail;// 电话
  private TextView tvDirectorEmailDetail;// 邮箱
  private TextView tvPositionConstructionDetail;// 职务说明
  private TextView mTvBithDateDetailDepartmentPerson;// 出生日期
  private TextView mTvBirthHomeDetailDepartmentPerson;// 家乡地
  private TextView mTvHomeAddressDetailDepartmentPerson;// 家庭住址
  private TextView mTvGraduateSchoolDetailDepartmentPerson;// 毕业院校
  private TextView mTvPersonalEnjoyDetailDepartmentPerson;// 个人喜好
  private TextView mTvBestVisitTimeDetailDepartmentPerson;// 最佳拜访时间
  private TextView mTvPersonalRequireDetailDepartmentPerson;// 个人需求
  private TextView mTvFamilyRelationDetailDepartmentPerson;// 家庭人员及关系
  private TextView mTvOtherRemarkDetailDepartmentPerson;// 其他说明与备注
  private DepartmentPerson staffInfo;
  private String mStatus;
  private SingleLineView slvWeChatNumber;
  private SingleLineView slvCustomer;
  private SingleLineView slvDepartment;

  public static Fragment newInstance(DepartmentPerson mDepartmentPerson) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, mDepartmentPerson);
    CustomerRelationStaffDetailFragment fragment = new CustomerRelationStaffDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(MyStringUtil.connect(R.string.customerContact1, R.string.detail1));
    staffInfo = (DepartmentPerson) getArguments().getSerializable(EXTRA_VALUE);
    mStatus = staffInfo != null ? staffInfo.getDataStatus() : "";
    mActivity = (BaseVolleyActivity) getActivity();
    // mStatus = SharedPreferencesUtil.getString(getActivity(),
    // SharedPreferencesUtil.DATA_STATUS, "");
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_department_staff_detail, container, false);
    tvDirectorNumberDetail =
        (TextView) view.findViewById(R.id.tv_directorNumber_detail_departmentPerson);
    tvDepartmentpersonDetail =
        (TextView) view.findViewById(R.id.tv_departmentperson_detail_departmentPerson);
    tv_personGender_detail =
        (TextView) view.findViewById(R.id.tv_personGender_detail_customerRelation);
    tvDirectordialDetail =
        (TextView) view.findViewById(R.id.tv_directordial_detail_departmentPerson);
    slvWeChatNumber = (SingleLineView) view.findViewById(R.id.slv_weChatNumber);
    slvCustomer = (SingleLineView) view.findViewById(R.id.slv_Customer);
    slvDepartment = (SingleLineView) view.findViewById(R.id.slv_department);
    tvDirectorEmailDetail =
        (TextView) view.findViewById(R.id.tv_directorEmail_detail_departmentPerson);
    tvPositionConstructionDetail =
        (TextView) view.findViewById(R.id.tv_positionConstruction_detail_departmentPerson);
    mTvBithDateDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_bithDate_detail_departmentPerson);
    mTvBirthHomeDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_birthHome_detail_departmentPerson);
    mTvHomeAddressDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_homeAddress_detail_departmentPerson);
    mTvGraduateSchoolDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_graduateSchool_detail_departmentPerson);
    mTvPersonalEnjoyDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_personalEnjoy_detail_departmentPerson);
    mTvBestVisitTimeDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_bestVisitTime_detail_departmentPerson);
    mTvPersonalRequireDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_personalRequire_detail_departmentPerson);
    mTvFamilyRelationDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_familyRelation_detail_departmentPerson);
    mTvOtherRemarkDetailDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_otherRemark_detail_departmentPerson);
    initView();
    DynamicConfigLab config =
        DynamicConfigLab.newInstance(mActivity, getString(R.string.module_deptColumns));
    config.autoConfigTitle(view);
    config.autoConfigVisiblity(view);
    return view;
  }

  private void initView() {
    String staffNo = staffInfo.getStaffNo();
    String staffName = staffInfo.getStaffName();
    String gender = staffInfo.getStaffGender();
    String dial = staffInfo.getContactNum();
    String email = staffInfo.getContactMail();
    String duty = staffInfo.getDutyDescript();
    String birthday = staffInfo.getBirthDate();
    String birthHome = staffInfo.getHomeArea();
    String homeAddress = staffInfo.getHomeAddress();
    String graduateSchool = staffInfo.getGraduateCollege();
    String personalEnjoy = staffInfo.getPersonalHobby();
    String bestVisitTime = staffInfo.getVisitTime();
    String personalRequire = staffInfo.getPersonalNeed();
    String familyRelation = staffInfo.getFamilyRelation();
    String otherRemark = staffInfo.getExplainRemark();

    if (!TextUtils.isEmpty(staffNo)) {
      tvDirectorNumberDetail.setText(staffNo);
    }
    if (!TextUtils.isEmpty(staffName)) {
      tvDepartmentpersonDetail.setText(staffName);
    }
    if (!TextUtils.isEmpty(gender)) {
      tv_personGender_detail.setText(gender);
    }
    if (!TextUtils.isEmpty(dial)) {
      tvDirectordialDetail.setText(dial);
    }
    slvWeChatNumber.setInputEnabled(false);
    slvCustomer.setInputEnabled(false);
    slvDepartment.setInputEnabled(false);
    slvWeChatNumber.setTextContent(staffInfo == null ? "" : staffInfo.getWeChatCode());
    slvCustomer.setTextContent(staffInfo == null ? "" : staffInfo.getBlongCustomerName());
    slvDepartment.setTextContent(staffInfo == null ? "" : staffInfo.getBlongOrgName());
    if (!TextUtils.isEmpty(email)) {
      tvDirectorEmailDetail.setText(email);
    }
    if (!TextUtils.isEmpty(duty)) {
      tvPositionConstructionDetail.setText(duty);
    }

    if (!TextUtils.isEmpty(birthday)) {
      mTvBithDateDetailDepartmentPerson.setText(birthday);
    }
    if (!TextUtils.isEmpty(birthHome)) {
      mTvBirthHomeDetailDepartmentPerson.setText(birthHome);
    }
    if (!TextUtils.isEmpty(homeAddress)) {
      mTvHomeAddressDetailDepartmentPerson.setText(homeAddress);
    }
    if (!TextUtils.isEmpty(graduateSchool)) {
      mTvGraduateSchoolDetailDepartmentPerson.setText(graduateSchool);
    }
    if (!TextUtils.isEmpty(personalEnjoy)) {
      mTvPersonalEnjoyDetailDepartmentPerson.setText(personalEnjoy);
    }
    if (!TextUtils.isEmpty(bestVisitTime)) {
      mTvBestVisitTimeDetailDepartmentPerson.setText(bestVisitTime);
    }
    if (!TextUtils.isEmpty(personalRequire)) {
      mTvPersonalRequireDetailDepartmentPerson.setText(personalRequire);
    }
    if (!TextUtils.isEmpty(familyRelation)) {
      mTvFamilyRelationDetailDepartmentPerson.setText(familyRelation);
    }
    if (!TextUtils.isEmpty(otherRemark)) {
      mTvOtherRemarkDetailDepartmentPerson.setText(otherRemark);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (!("publish".equalsIgnoreCase(mStatus))) {
      inflater.inflate(R.menu.menu_department_edit, menu);
    } else {
      inflater.inflate(R.menu.menu_customerrelation_back, menu);
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    // 部门登记人Id
    String regStaffId = staffInfo.getRegStaffId();
    boolean isCreater = CurrentUser.newInstance(getActivity()).isCreater(regStaffId);

    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_delete:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        }
        showDialog(REQUEST_DELETE);

        break;
      case R.id.menu_item_alter:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        }
        Intent intent = new Intent(getActivity(), CustomerRelationStaffDetailEditActivity.class);
        intent.putExtra(CustomerRelationStaffDetailEditFragment.EXTRA_VALUE, staffInfo);
        startActivityForResult(intent, REQUEST_ALTER);
        break;
      case R.id.menu_item_confirm:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        }
        showDialog(REQUESUT_SUBMIT);

        break;

      case R.id.menu_item_back:
        if (!isCreater) {// 不是创建人不允许更改操作。
          Toast.makeText(getActivity(), R.string.not_founder, Toast.LENGTH_SHORT).show();
          return true;
        } else {
          staffChek();
        }
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  // 员工审核
  private void staffChek() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_STAFF_CHECK);
    HashMap<String, String> mStaff = new HashMap<>();

    String mId = "'" + staffInfo.getId() + "'";
    mStaff.put("ids", mId);
    if ("publish".equalsIgnoreCase(mStatus)) {
      mStaff.put("dataStatus", "newback");
    } else {
      mStaff.put("dataStatus", "publish");
    }

    mActivity.volleyPost(url, mStaff, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          LogUtil.i(TAG, "response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {

      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;

      case REQUESUT_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.submitConfirm);
        break;

      default:
        return;
    }

    dialog.setTargetFragment(CustomerRelationStaffDetailFragment.this, type);
    dialog.show(fm, "");
  }

  // 删除
  private void volleyPostDelete() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_STAFF_DELETE);
    String ids = staffInfo.getId();// 员工id
    mDepartmentDetail = new HashMap<>();
    mDepartmentDetail.put("ids", ids);
    Log.i(TAG, "params=" + mDepartmentDetail.toString());
    mActivity.volleyPost(url, mDepartmentDetail, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          LogUtil.i(TAG, "response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {
      case REQUEST_ALTER:// 更改.
        staffInfo = (DepartmentPerson) data.getSerializableExtra(
            CustomerRelationStaffDetailEditFragment.EXTRA_MEMBER);
        initView();
        getActivity().setResult(Activity.RESULT_OK);
        break;
      case REQUEST_DELETE:
        volleyPostDelete();

      case REQUESUT_SUBMIT:
        staffChek();
        break;
      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
